<template>
  <view class="login-container">
    <view class="center">
      <u--image
        :showLoading="true"
        src="/static/u6.png"
        width="185px"
        height="49px"
        mode="aspectFit"
      ></u--image>
      <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
      <u--form labelPosition="left" :model="model1" :rules="rules" ref="form1">
        <u-form-item
          label=""
          prop="userInfo.phone"
          borderBottom="false"
          ref="item1"
        >
          <u--input
            v-model="model1.userInfo.phone"
            placeholder="手机号"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item
          v-if="loginFlag"
          label=""
          prop="userInfo.password"
          borderBottom="false"
          ref="item1"
        >
          <u--input
            v-model="model1.userInfo.password"
            placeholder="密码"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item
          v-else
          label=""
          id="code-item"
          prop="userInfo.code"
          labelWidth="80"
          borderBottom="false"
        >
          <u--input
            v-model="model1.userInfo.code"
            border="none"
            placeholder="请填写验证码"
          ></u--input>
          <u-button
            slot="right"
            @tap="getCode"
            :text="tips"
            type="success"
            size="mini"
            :disabled="disabled1"
          ></u-button>
        </u-form-item>
      </u--form>
      <view class="bottom">
        <u-code
          ref="uCode"
          @change="codeChange"
          seconds="60"
          @start="disabled1 = true"
          @end="disabled1 = false"
        ></u-code>
        <u-button class="login_btn" @click="login" type="primary"
          >登&nbsp;&nbsp;&nbsp;&nbsp;录</u-button
        >
        <view class="code">
          <text @tap.prevent="loginByCode">{{
            this.loginFlag ? "验证码登录" : "密码登录"
          }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { login } from "@/common/api.js";
import { mapMutations, mapActions } from "vuex";
export default {
  data() {
    return {
      //加密字符
      chars: [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      //是否禁用发送验证码按钮
      disabled1: false,
      //按钮文字显示
      tips: "获取验证码",
      //切换密码登录和验证码登录
      loginFlag: true,
      model1: {
        userInfo: {
          phone: "13432385803",
          password: "12345",
          code: "",
        },
      },
      rules: {
        "userInfo.phone": [
          {
            type: "number",
            required: true,
            message: "请填写正确的手机号",
            trigger: "blur",
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.phone()就是返回true或者false的
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: "blur",
          },
        ],
        "userInfo.password": {
          type: "string",
          required: true,
          message: "请填写密码",
          trigger: ["blur", "change"],
        },
        "userInfo.code": {
          type: "string",
          required: true,
          len: 4,
          message: "请填写4位验证码",
          trigger: ["blur"],
        },
      },
      radio: "",
      switchVal: false,
    };
  },
  methods: {
    ...mapMutations("user", ["setUserInfo"]),
    login() {
      this.$refs.form1
        .validate()
        .then((res) => {
          uni.showLoading({
            title: "登录中",
          });
          if (
            this.model1.userInfo.phone === "13432385803" &&
            this.model1.userInfo.password == "12345"
          ) {
            uni.navigateTo({
              url: "/pages/index/index",
              animationType: "none",
            });
          }
          let sendUserInfo = {
            phone: this.model1.userInfo.phone,
            password: this.encode(this.model1.userInfo.password),
          };
          login(sendUserInfo).then((res) => {
            uni.hideLoading();
			document.cookie = "access-token="+res;
			getuserInfo().then(res=>{
				this.setUserInfo(res);
				uni.navigateTo({
				  url: "/pages/index/index",
				  animationType: "none",
				});
			}).catch(err=>{
				uni.$u.toast('获取用户信息失败')
			})
			
          });
        })
        .catch((errors) => {
          uni.$u.toast("校验失败");
        });
    },
    //切换验证码登录
    loginByCode() {
      this.loginFlag = !this.loginFlag;
    },
    //获取验证码
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: "正在获取验证码",
        });
        setTimeout(() => {
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          uni.$u.toast("验证码已发送");
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start();
        }, 2000);
      } else {
        uni.$u.toast("倒计时结束后再发送");
      }
    },
    codeChange(text) {
      this.tips = text;
    },
    //获取随机码
    generateMixed(n) {
      let res = "";
      for (var i = 0; i < n; i++) {
        let id = Math.ceil(Math.random() * 35);
        res += this.chars[id];
      }
      return res;
    },
    //加密
    encode(txt) {
      let start, end;
      start = this.generateMixed(5);
      end = this.generateMixed(5);
      let enTxt = new Array();
      enTxt.push(start);
      let i, s;
      for (i = 0; i < txt.length; i++) {
        enTxt.push(txt.charCodeAt(i).toString(16));
      }
      enTxt.push(end);
      return enTxt.join("\\");
    },
  },
};
</script>

<style lang="scss">
@import "@/static/css/_px2vw.scss";
.login-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-content: center;
  .center {
    width: vw(400);
    height: 100vh;
    margin: auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    .u-form {
      width: 100%;
      margin-top: vw(50);
      .u-form-item {
        position: relative;
        border: 1px solid rgb(170, 170, 170);
        width: 100%;
        height: vw(50);
        line-height: vw(50);
        font-size: vw(13);
        padding-left: vw(2);
        & + .u-form-item {
          margin-top: vw(40);
        }
        .u-button {
          width: vw(100);
          height: vw(40);
        }
      }
    }
    .bottom {
      width: 100%;
      margin-top: vw(35);
      .login_btn {
        width: 100%;
        height: vw(40);
        font-size: vw(18);
        border-radius: vw(5);
      }
      .code {
        margin-top: vw(45);
        color: #0078ff;
        font-size: vw(14);
      }
    }
  }
}
</style>
